<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        padding: 0;
        margin: 0;
      }

      .wrap {
        width: 300px;
        height: 350px;
        margin: 100px auto;
        overflow: hidden;
        border: 2px solid #ccc;
      }

      .wrap .bg {
        width: 900px;
        height: 300px;
        background-color: #bbb;
        display: flex;
        /* transform: translateX(-300px); */
      }

      .boxWrap {
        width: 300px;
        height: 50px;
        display: flex;
      }

      .boxWrap > button {
        width: 100px;
        height: 100%;
      }
      .bg > div {
        width: 300px;
        height: 100%;
      }
      .bg > div:nth-of-type(1) {
        background-color: red;
      }
      .bg > div:nth-of-type(2) {
        background-color: blue;
      }
      .bg > div:nth-of-type(3) {
        background-color: yellow;
      }
    </style>
  </head>
  <body>
    <div class="wrap">
      <div class="bg">
        <div></div>
        <div></div>
        <div></div>
      </div>
      <div class="boxWrap">
        <button>1</button>
        <button>2</button>
        <button>3</button>
      </div>
    </div>
  </body>
  <script>
    // let aBtn = document.querySelectorAll("button");
    // let oDiv = document.querySelector(".bg");
    // aBtn.forEach(function (btn, index) {
    //   btn.onclick = function () {
    //     oDiv.style.transform = `translateX(-${3 * index}00px)`;
    //     console.log(`点击${index}`);
    //   };
    // });
    let box = document.querySelector(".wrap");
    function Tab(dom) {
      this.aBtn = dom.querySelectorAll("button");
      //console.log(this.aBtn); //返回的是一个节点对象的伪数组
      this.oDiv = dom.querySelector(".bg");
      this.fn = () => {
        // console.log(this, "fn");
        this.aBtn.forEach((btn, index) => {
          // console.log(this, "foreach");
          //箭头函数改变this指向，使用构造函数内的属性
          btn.onclick = () => {
            // console.log(this, "onclick");
            console.log(index);
            //箭头函数改变this指向，使用构造函数内的属性
            console.log(this.oDiv);
            this.oDiv.style.transform = `translateX(-${3 * index}00px)`;
          };
        });
      };
    }
    let tab = new Tab(box);
    tab.fn();
  </script>
</html>
